package com.sos.exception;

import com.sos.model.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomException.class)
    public ResultVO<?> handleCustomException(CustomException e) {
        log.error("自定义异常: {}", e.getMessage());
        return ResultVO.error(e.getCode(), e.getMessage());
    }
    @ExceptionHandler(MissingRequestHeaderException.class)
    public ResultVO<?> handleMissingRequestHeaderException(MissingRequestHeaderException e) {
        log.error("缺少请求头: {}", e.getMessage());
        return ResultVO.error(ErrorCode.PARAM_ERROR.getCode(), "缺少必要的请求头：" + e.getHeaderName());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMsg.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append(";");
        }
        log.error("参数校验异常: {}", errorMsg.toString());
        return ResultVO.error(ErrorCode.PARAM_ERROR.getCode(), errorMsg.toString());
    }

    @ExceptionHandler(Exception.class)
    public ResultVO<?> handleException(Exception e) {
        log.error("系统异常: ", e);
        return ResultVO.error(ErrorCode.SYSTEM_ERROR.getCode(), ErrorCode.SYSTEM_ERROR.getMessage());
    }
}
